import { App } from 'vue';
import { I18nOptions, createI18n } from 'vue-i18n';

import { SupportLanguage } from '@/types/enums';

interface LangModule {
  message: Recordable;
}

export let i18n: ReturnType<typeof createI18n>;

export const setupI18n = async (app: App, options: I18nOptions = {}) => {
  i18n = createI18n({
    ...options,
    legacy: false,
    fallbackLocale: 'en',
  });
  const defaultLang = SupportLanguage.en;
  await loadLocaleMessages(defaultLang);
  app.use(i18n);
  return i18n;
};

export function setI18nLanguage(locale: SupportLanguage) {
  if (i18n.mode === 'legacy') {
    i18n.global.locale = locale;
  } else {
    (i18n.global.locale as WritableComputedRef<string>).value = locale;
  }
  document.querySelector('html')?.setAttribute('lang', locale);
}

const loadedLocaleMessages: SupportLanguage[] = [];

export async function loadLocaleMessages(locale: SupportLanguage) {
  const globalI18n = i18n.global;
  const currentLocale = unref(globalI18n.locale);
  if (currentLocale === locale) {
    return;
  }
  if (!loadedLocaleMessages.includes(locale)) {
    const messages = ((await import(`./lang/${locale}.ts`)) as any).default as LangModule;
    i18n.global.setLocaleMessage(locale, messages.message);
    setI18nLanguage(locale);
    loadedLocaleMessages.push(locale);
  }
}
